package week_01;

import java.util.Arrays;

public class ReverseNodesInKGroup_25 {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode head2 = new ListNode();
        ListNode L = head;
        ListNode preL = head2;
        ListNode R = null;
        ListNode lastR = null;
        int d = 0;
        while (head != null) {
            ListNode next = head.next;
            R = head;
            lastR = R.next;
            System.out.println(R.val);
            if (d == k - 1) {

                ListNode[] revs = reverse(L, R, k);
                preL.next = revs[0];
                revs[1].next = lastR;
                d = -1;
                // 组内反转完
                L = lastR;
                preL = revs[1];
            }
            d++;

            head = next;
        }
        printList(head2);
        return head2.next;
    }

    public ListNode[] reverse(ListNode L, ListNode R, int k) {
        System.out.println("reverse:" + L.val + "::" + R.val);
        ListNode tail = L;
        ListNode head = null;
        while (k > 0) {
            ListNode next = L.next;
            L.next = head;
            head = L;
            L = next;
            k--;
        }
        ListNode[] ans = {head, tail};
        return ans;
    }

    public static void main(String[] args) {
        ReverseNodesInKGroup_25 solution = new ReverseNodesInKGroup_25();
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
        ListNode root = buildListNode(arr);
        printList(root);
        ListNode node = solution.reverseKGroup(root, 3);
        printList(node);
    }

    private static void printList(ListNode root) {
        while (root != null) {
            System.out.print(root.val + "->");
            root = root.next;
        }
        System.out.println();
    }

    private static ListNode buildListNode(int[] arr) {
        ListNode head = new ListNode();
        ListNode tail = head;
        for (int i = 0; i < arr.length; i++) {
            ListNode node = new ListNode();
            node.val = arr[i];
            tail.next = node;
            tail = tail.next;
        }
        return head.next;
    }
}
